package com.qb.common.widget
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
class CircleImageView:AppCompatImageView {
    private var borderWidth: Float = 1f // 边框宽度
    private var borderColor: String = "#DDDDDD" // 边框颜色
    private val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val imagePaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val path = Path()
    private val rectF = RectF()

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init()
    }

    private fun init() {
        borderWidth = dpToPx(1f) // 默认边框宽度为1dp
        borderPaint.style = Paint.Style.STROKE
        borderPaint.strokeWidth = borderWidth
        borderPaint.color = Color.parseColor(borderColor)
        imagePaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
    }

    override fun onDraw(canvas: Canvas) {
        val radius = Math.min(width, height) / 2f
        val centerX = width / 2f
        val centerY = height / 2f

        // 绘制圆形边框
        canvas.drawCircle(centerX, centerY, radius - borderWidth / 2f, borderPaint)

        // 使用路径裁剪绘制圆形图像
        path.reset()
        path.addCircle(centerX, centerY, radius - borderWidth, Path.Direction.CW)
        canvas.save()
        canvas.clipPath(path)
        super.onDraw(canvas)
        canvas.restore()
    }

    // 设置边框宽度和颜色
    fun setBorderWidthAndColor(width: Float, color: String) {
        borderWidth = dpToPx(width)
        borderColor = color
        borderPaint.strokeWidth = borderWidth
        borderPaint.color = Color.parseColor(borderColor)
        invalidate()
    }

    // 将dp转换为像素
    private fun dpToPx(dp: Float): Float {
        val density = resources.displayMetrics.density
        return dp * density
    }
}